#include "info_init.h"
#include "userobject.h"

#include <QJsonDocument>
#include <QJsonValue>
#include <QJsonObject>
#include <QJsonArray>

Info_Init::Info_Init(Http_Post *parent) :
	Http_Post(parent)
{
	std::mt19937 eng(time(NULL));
	std::uniform_int_distribution<long long> deviceId(1615250492, 519062714508114);
	m_deviceId = QString::number(deviceId(eng));
}

Info_Init::~Info_Init()
{

}

void Info_Init::m_clear()
{
	Q_FOREACH (QObject* obj, m_contactList) {
		if (obj) {
			delete obj;
			obj = Q_NULLPTR;
		}
	}
	m_contactList.clear();
	m_map.clear();
}

void Info_Init::postV2(QString uin, QString sid, QString ticket)
{
	m_clear();

	QString url = WX_V2_SERVER_HOST + WX_CGI_PATH + "webwxinit?pass_ticket=" +
		ticket + "&r=" + QString::number(time(NULL));

#if QWX_DEBUG
	qDebug() << "DEBUG:" << __PRETTY_FUNCTION__ << url;
#endif

	QString json = "{\"BaseRequest\":{\"Uin\":\"" + uin + "\",\"Sid\":\"" +
		sid + "\",\"Skey\":\"\",\"DeviceID\":\"" + m_deviceId + "\"}}";

#if QWX_DEBUG
	qDebug() << "DEBUG:" << __PRETTY_FUNCTION__ << json;
#endif

	Http_Post::post(url, json, true);
}

void Info_Init::finished(QNetworkReply* reply)
{
	QString replyStr = QString(reply->readAll());

#if QWX_DEBUG
	QFile file("init.json");
	if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
		QTextStream out(&file);
		out << replyStr;
		file.close();
	}
	qDebug() << "DEBUG:" << __PRETTY_FUNCTION__;
	//qDebug() << "DEBUG:" << replyStr;
#endif

	QJsonDocument doc = QJsonDocument::fromJson(replyStr.toUtf8());
	if (!doc.isObject()) {
		Q_EMIT error();
		return;
	}

	QJsonObject obj = doc.object();

	QJsonObject ret = obj["BaseResponse"].toObject();
	if(ret["Ret"].toString() != 0) {
		Q_EMIT error();
		return;
	}


	QJsonObject user = obj["User"].toObject();
	m_loginUserName = user["UserName"].toString();
	m_loginNickName = user["NickName"].toString();
#if QWX_DEBUG
	qDebug() << "DEBUG:" << m_loginNickName << "[" << m_loginUserName << "]";
#endif


#if 0
	// 下一个接口去获取所有的联系人信息
	Q_FOREACH (const QJsonValue & val, obj["ContactList"].toArray()) {
		QJsonObject user = val.toObject();
		QString userName = user["UserName"].toString();
		QString nickName = user["NickName"].toString();
		if (!m_map.contains(userName)) {
			m_contactList.append(new UserObject(
				userName,
				nickName,
				WX_V2_SERVER_HOST + user["HeadImgUrl"].toString()));
		}
		m_map.insert(userName, nickName);
	}
	Q_EMIT contactListChanged();
#endif


	QString skey = obj["SKey"].toString();
#if QWX_DEBUG
	qDebug() << "DEBUG:" << __PRETTY_FUNCTION__ << skey;
#endif


	QStringList syncKey;
	Q_FOREACH (const QJsonValue & val, obj["SyncKey"].toObject()["List"].toArray()) {
		syncKey.append(QString::number(val.toObject()["Key"].toInt()) + "|" +
				QString::number(val.toObject()["Val"].toInt()));
	}

	Q_EMIT init_ok(m_loginUserName, m_loginNickName, skey, syncKey, m_deviceId);
}
